<template>
  <div class="resume-list-page">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">我的简历</h1>
        <el-button type="primary" @click="createResume">
          <el-icon><plus /></el-icon>
          创建新简历
        </el-button>
      </div>
      
      <!-- 简历提示 -->
      <div class="resume-tips">
        <el-alert
          type="info"
          :closable="false"
          show-icon
        >
          <template #title>
            <span class="tip-title">简历小提示</span>
          </template>
          <div class="tip-content">
            <p>完善的简历可以提高您的求职成功率。请确保您的简历包含以下信息：</p>
            <ul>
              <li>准确完整的个人信息和联系方式</li>
              <li>与目标职位相关的工作经历和项目经验</li>
              <li>教育背景和专业技能</li>
              <li>相关证书和荣誉奖项</li>
            </ul>
          </div>
        </el-alert>
      </div>
      
      <!-- 简历列表 -->
      <div class="resume-list" v-loading="loading">
        <template v-if="resumes.length > 0">
          <div 
            v-for="resume in resumes" 
            :key="resume.id"
            class="resume-card"
          >
            <div class="resume-info">
              <div class="resume-header">
                <h2 class="resume-name">{{ resume.name }}</h2>
                <el-tag 
                  :type="resume.isDefault ? 'success' : 'info'"
                  size="small"
                >
                  {{ resume.isDefault ? '默认简历' : '普通简历' }}
                </el-tag>
              </div>
              
              <div class="resume-meta">
                <div class="meta-item">
                  <span class="label">更新时间：</span>
                  <span class="value">{{ formatDate(resume.updateTime) }}</span>
                </div>
              </div>
              
            
            </div>
            
            <div class="resume-actions">
              <el-button type="primary" @click="editResume(resume.id)">
                编辑
              </el-button>
              <el-button @click="previewResume(resume.id)">
                预览
              </el-button>
              <el-dropdown @command="handleCommand($event, resume)">
                <el-button>
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item 
                      v-if="!resume.isDefault" 
                      command="setDefault"
                    >
                      设为默认
                    </el-dropdown-item>
                    <el-dropdown-item command="download">下载简历</el-dropdown-item>
                    <el-dropdown-item command="share">分享简历</el-dropdown-item>
                    <el-dropdown-item command="rename">重命名</el-dropdown-item>
                    <el-dropdown-item 
                      command="delete" 
                      class="danger-item"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </template>
        
        <el-empty 
          v-else-if="!loading" 
          description="您还没有创建任何简历"
        >
          <el-button type="primary" @click="createResume">
            创建第一份简历
          </el-button>
        </el-empty>
      </div>
    </div>
    
    <!-- 重命名对话框 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名简历"
      width="400px"
    >
      <el-form :model="renameForm" label-width="80px">
        <el-form-item label="简历名称">
          <el-input v-model="renameForm.name" placeholder="请输入简历名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog
      v-model="shareDialogVisible"
      title="分享简历"
      width="400px"
    >
      <div class="share-options">
        <div class="share-link">
          <p>分享链接</p>
          <el-input v-model="shareLink" readonly>
            <template #append>
              <el-button @click="copyShareLink">复制</el-button>
            </template>
          </el-input>
        </div>
        
        <div class="share-qrcode">
          <p>扫码分享</p>
          <div class="qrcode-placeholder">
            <!-- 这里可以集成二维码生成组件 -->
            <div class="mock-qrcode"></div>
          </div>
        </div>
        
        <div class="share-platforms">
          <p>分享到社交平台</p>
          <div class="platform-buttons">
            <el-button size="small">
              <el-icon><promotion /></el-icon>微信
            </el-button>
            <el-button size="small">
              <el-icon><promotion /></el-icon>微博
            </el-button>
            <el-button size="small">
              <el-icon><promotion /></el-icon>QQ
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="简历预览"
      width="900px"
      top="5vh"
      append-to-body
      center
      destroy-on-close
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      class="resume-preview-dialog"
    >
      <div class="resume-preview">
        <div class="preview-header">
          <h3 class="preview-title">{{ previewResumeData?.basic?.name || '我' }}的简历</h3>
          <p class="preview-subtitle">创建于 {{ formatCurrentDate() }}</p>
          
          <div class="preview-actions">
            <el-button type="primary" @click="downloadResume(previewResumeId)" size="large">
              <el-icon><download /></el-icon>
              下载 PDF 简历
            </el-button>
            <el-button @click="previewVisible = false" plain size="large">
              <el-icon><close /></el-icon>
              关闭预览
            </el-button>
          </div>
        </div>
        
        <div class="preview-container">
          <div class="paper-effect" v-loading="previewLoading">
            <resume-preview-content v-if="previewResumeData" :resume="previewResumeData" />
            <el-empty v-else description="简历数据加载中..." />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="preview-footer">
          <p class="preview-tip">提示：您可以下载 PDF 格式简历或关闭预览继续编辑</p>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Star, 
  MessageBox, 
  InfoFilled, 
  ArrowDown,
  Promotion,
  Download,
  Close
} from '@element-plus/icons-vue'
import { getResumeList, deleteResume, setDefaultResume, getResumeDetail } from '@/api/resume'
import ResumePreviewContent from '@/components/resume/ResumePreviewContent.vue'

const router = useRouter()

// 数据
const loading = ref(false)
const resumes = ref([])
const renameDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const currentResumeId = ref(null)
const renameForm = ref({ name: '' })
const shareLink = ref('')

// 预览相关
const previewVisible = ref(false)
const previewResumeId = ref(null)
const previewResumeData = ref(null)
const previewLoading = ref(false)

// 获取简历列表
const fetchResumes = async () => {
  loading.value = true
  try {
    const res = await getResumeList()
    if (res.code === 200) {
      resumes.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取简历列表失败')
    }
  } catch (error) {
    console.error('获取简历列表出错:', error)
    ElMessage.error('获取简历列表失败')
  } finally {
    loading.value = false
  }
}

// 获取完整度状态
const getCompletenessStatus = (percentage) => {
  if (percentage < 60) return 'exception'
  if (percentage < 80) return 'warning'
  return 'success'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 格式化当前日期
const formatCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 创建新简历
const createResume = () => {
  router.push('/resumes/create')
}

// 编辑简历
const editResume = (id) => {
  router.push(`/resumes/${id}/edit`)
}

// 预览简历
const previewResume = async (id) => {
  previewResumeId.value = id
  previewLoading.value = true
  previewVisible.value = true
  previewResumeData.value = null
  
  try {
    const response = await getResumeDetail(id)
    console.log('简历API返回数据:', response)
    
    if (response && response.code === 200) {
      // 将后端数据转换为前端需要的结构
      const data = response.data

      // 解析职业期望 (jobExpectation)
      const jobExpectationData = parseJobExpectation(data.jobExpectation)
      
      // 解析工作经历
      const parsedExperiences = parseExperiences(data.workExperience)
      
      // 解析项目经历
      const parsedProjects = parseProjects(data.projectExperience)
      
      // 解析技能和证书
      const skillsData = {
        skillTags: data.skills ? data.skills.split(',').map(s => s.trim()) : [],
        certificates: data.certificates ? data.certificates.split(',').map(c => c.trim()) : [],
        languages: data.languages ? data.languages.split(',').map(l => l.trim()) : []
      }
      
      // 构建教育信息
      const educationsData = [{
        school: data.school || '',
        major: data.major || '',
        degree: data.education || '',
        graduationYear: data.graduationYear || '',
        startDate: data.schoolStartDate || '',
        endDate: data.schoolEndDate || '',
        description: data.schoolExperience || ''
      }]
      
      // 构建基本信息
      const basicData = {
        name: data.name || '',
        phone: data.phone || '',
        email: data.email || '',
        gender: data.gender || '',
        selfIntroduction: data.selfEvaluation || '',
        title: data.title || '我的简历',
        location: data.location || '',
        birthday: data.birthday || '',
        experience: data.workYears || '',
        ...jobExpectationData
      }
      
      // 创建完整的数据对象
      const formattedResumeData = {
        id: data.id,
        basic: basicData,
        educations: educationsData,
        experiences: parsedExperiences,
        projects: parsedProjects,
        skills: skillsData
      }
      
      console.log('转换后的简历数据:', formattedResumeData)
      previewResumeData.value = formattedResumeData
    } else {
      ElMessage.error(response?.message || '获取简历详情失败')
    }
  } catch (error) {
    console.error('获取简历详情出错:', error)
    ElMessage.error('获取简历详情失败')
  } finally {
    previewLoading.value = false
  }
}

// 解析职业期望
const parseJobExpectation = (jobExpectationStr) => {
  if (!jobExpectationStr) return {}
  
  try {
    const jobExpectation = JSON.parse(jobExpectationStr)
    return {
      currentStatus: jobExpectation.status || '',
      expectSalary: jobExpectation.salary || '',
      expectLocation: jobExpectation.location || ''
    }
  } catch (e) {
    console.error('解析职业期望失败:', e)
    return {}
  }
}

// 解析工作经历
const parseExperiences = (experiencesStr) => {
  if (!experiencesStr) return []
  
  const experiences = []
  
  // 尝试解析JSON格式
  const experienceBlocks = experiencesStr.split('\n\n')
  
  experienceBlocks.forEach(block => {
    if (!block.trim()) return
    
    try {
      // 首先尝试解析JSON
      const expObj = JSON.parse(block)
      experiences.push({
        company: expObj.company || '',
        position: expObj.position || '',
        startDate: expObj.startDate || '',
        endDate: expObj.endDate || '',
        description: expObj.description || ''
      })
    } catch (e) {
      // 如果JSON解析失败，尝试传统格式
      const parts = block.split('\n')
      if (parts.length > 0) {
        const headerParts = parts[0].split('-')
        if (headerParts.length >= 3) {
          const company = headerParts[0] || ''
          const position = headerParts[1] || ''
          const dateRange = headerParts[2] || ''
          const dateParts = dateRange.split('至')
          
          let description = ''
          if (parts.length > 1) {
            description = parts.slice(1).join('\n')
          }
          
          experiences.push({
            company,
            position,
            startDate: dateParts[0] || '',
            endDate: dateParts.length > 1 ? dateParts[1] : '至今',
            description
          })
        }
      }
    }
  })
  
  return experiences
}

// 解析项目经历
const parseProjects = (projectsStr) => {
  if (!projectsStr) return []
  
  const projects = []
  
  // 尝试解析JSON格式
  const projectBlocks = projectsStr.split('\n\n')
  
  projectBlocks.forEach(block => {
    if (!block.trim()) return
    
    try {
      // 首先尝试解析JSON
      const projObj = JSON.parse(block)
      projects.push({
        name: projObj.name || '',
        role: projObj.role || '',
        startDate: projObj.startDate || '',
        endDate: projObj.endDate || '',
        description: projObj.description || ''
      })
    } catch (e) {
      // 如果JSON解析失败，尝试传统格式
      const parts = block.split('\n')
      if (parts.length > 0) {
        const headerParts = parts[0].split('-')
        if (headerParts.length >= 3) {
          const name = headerParts[0] || ''
          const role = headerParts[1] || ''
          const dateRange = headerParts[2] || ''
          const dateParts = dateRange.split('至')
          
          let description = ''
          if (parts.length > 1) {
            description = parts.slice(1).join('\n')
          }
          
          projects.push({
            name,
            role,
            startDate: dateParts[0] || '',
            endDate: dateParts.length > 1 ? dateParts[1] : '至今',
            description
          })
        }
      }
    }
  })
  
  return projects
}

// 处理下拉菜单命令
const handleCommand = (command, resume) => {
  switch (command) {
    case 'setDefault':
      handleSetDefault(resume.id)
      break
    case 'download':
      downloadResume(resume.id)
      break
    case 'share':
      shareResume(resume.id)
      break
    case 'rename':
      openRenameDialog(resume)
      break
    case 'delete':
      handleDeleteResume(resume.id)
      break
  }
}

// 设置默认简历
const handleSetDefault = async (id) => {
  try {
    const res = await setDefaultResume(id)
    if (res.code === 200) {
      ElMessage.success('设置成功')
      fetchResumes() // 重新获取列表
    } else {
      ElMessage.error(res.message || '设置失败')
    }
  } catch (error) {
    console.error('设置默认简历出错:', error)
    ElMessage.error('设置失败')
  }
}

// 下载简历
const downloadResume = async (id) => {
  try {
    // 实际应用中应该调用API
    // await resumeApi.downloadResume(id)
    
    ElMessage.success('简历下载中，请稍候')
  } catch (error) {
    console.error('下载简历失败', error)
    ElMessage.error('下载失败，请稍后再试')
  }
}

// 打开重命名对话框
const openRenameDialog = (resume) => {
  currentResumeId.value = resume.id
  renameForm.value.name = resume.name
  renameDialogVisible.value = true
}

// 确认重命名
const confirmRename = async () => {
  if (!renameForm.value.name.trim()) {
    ElMessage.warning('简历名称不能为空')
    return
  }
  
  try {
    // 实际应用中应该调用API
    // await resumeApi.renameResume(currentResumeId.value, renameForm.value.name)
    
    // 更新本地状态
    const resume = resumes.value.find(r => r.id === currentResumeId.value)
    if (resume) {
      resume.name = renameForm.value.name
    }
    
    renameDialogVisible.value = false
    ElMessage.success('简历重命名成功')
  } catch (error) {
    console.error('重命名简历失败', error)
    ElMessage.error('重命名失败，请稍后再试')
  }
}

// 分享简历
const shareResume = (id) => {
  currentResumeId.value = id
  shareLink.value = `https://joblinker.com/resumes/shared/${id}`
  shareDialogVisible.value = true
}

// 复制分享链接
const copyShareLink = () => {
  navigator.clipboard.writeText(shareLink.value)
    .then(() => {
      ElMessage.success('链接已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败', err)
      ElMessage.error('复制失败，请手动复制')
    })
}

// 删除简历
const handleDeleteResume = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除此简历吗？此操作不可恢复', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteResume(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchResumes() // 重新获取列表
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除简历出错:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  fetchResumes()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.resume-list-page {
  padding: var(--spacing-xl) 0;
}

// 页面标题
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  
  .page-title {
    font-size: 1.8rem;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
  }
}

// 简历提示
.resume-tips {
  margin-bottom: var(--spacing-xl);
  
  .tip-title {
    font-weight: 600;
  }
  
  .tip-content {
    color: var(--text-secondary);
    line-height: 1.6;
    
    ul {
      margin-top: var(--spacing-xs);
      padding-left: var(--spacing-lg);
    }
  }
}

// 简历列表
.resume-list {
  padding: var(--spacing-xl) 0;
  
  .resume-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    border-radius: var(--border-radius);
    padding: var(--spacing-lg);
    margin-bottom: var(--spacing-md);
    box-shadow: var(--box-shadow-sm);
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .resume-info {
      flex-grow: 1;
      
      .resume-header {
        display: flex;
        align-items: center;
        margin-bottom: var(--spacing-md);
        
        .resume-name {
          font-size: 1.2rem;
          font-weight: 600;
          color: var(--text-primary);
          margin: 0;
          margin-right: var(--spacing-md);
        }
      }
      
      .resume-meta {
        margin-bottom: var(--spacing-md);
        
        .meta-item {
          display: flex;
          align-items: center;
          margin-bottom: var(--spacing-xs);
          
          .label {
            width: 80px;
            font-size: 0.9rem;
            color: var(--text-secondary);
          }
          
          .value {
            flex-grow: 1;
            font-size: 0.9rem;
            color: var(--text-primary);
          }
        }
      }
      
      .resume-stats {
        display: flex;
        gap: var(--spacing-xl);
        
        .stat-item {
          display: flex;
          align-items: center;
          
          .stat-icon {
            color: var(--primary-color);
            margin-right: var(--spacing-xs);
          }
          
          .stat-value {
            font-weight: 600;
            color: var(--text-primary);
            margin-right: var(--spacing-xs);
          }
          
          .stat-label {
            font-size: 0.9rem;
            color: var(--text-secondary);
          }
        }
      }
    }
    
    .resume-actions {
      display: flex;
      gap: var(--spacing-sm);
    }
  }
}

// 重命名对话框
.rename-dialog {
  .el-form-item {
    margin-bottom: var(--spacing-md);
  }
}

// 分享对话框
.share-options {
  .share-link, .share-qrcode, .share-platforms {
    margin-bottom: var(--spacing-lg);
    
    &:last-child {
      margin-bottom: 0;
    }
    
    p {
      font-size: 0.95rem;
      margin-bottom: var(--spacing-sm);
      color: var(--text-secondary);
    }
  }
  
  .qrcode-placeholder {
    display: flex;
    justify-content: center;
    
    .mock-qrcode {
      width: 150px;
      height: 150px;
      background: var(--bg-light);
      border: 1px dashed var(--border-color);
      display: flex;
      align-items: center;
      justify-content: center;
      
      &::after {
        content: 'QR Code';
        color: var(--text-secondary);
      }
    }
  }
  
  .platform-buttons {
    display: flex;
    gap: var(--spacing-sm);
  }
}

// 预览对话框样式
.resume-preview-dialog {
  :deep(.el-dialog__header) {
    padding: var(--spacing-lg);
    border-bottom: 1px solid var(--border-color-light);
    
    .el-dialog__title {
      font-size: var(--font-size-xl);
      font-weight: 600;
      color: var(--text-primary);
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
  
  :deep(.el-dialog__footer) {
    padding: var(--spacing-md);
    border-top: 1px solid var(--border-color-light);
    background-color: var(--color-background-light);
  }
}

.resume-preview {
  .preview-header {
    background-color: var(--color-primary-light);
    padding: var(--spacing-lg);
    border-bottom: 1px solid var(--border-color-light);
    text-align: center;
    
    .preview-title {
      font-size: var(--font-size-xl);
      font-weight: 600;
      color: var(--color-primary);
      margin: 0 0 var(--spacing-xs);
    }
    
    .preview-subtitle {
      color: var(--text-secondary);
      margin: 0 0 var(--spacing-md);
      font-size: var(--font-size-sm);
    }
    
    .preview-actions {
      display: flex;
      justify-content: center;
      gap: var(--spacing-md);
      margin-top: var(--spacing-md);
    }
  }
  
  .preview-container {
    padding: var(--spacing-lg);
    background: linear-gradient(to right, #f5f7fa, #f1f4f9);
    max-height: 65vh;
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 8px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #ccc;
      border-radius: 4px;
    }
    
    &::-webkit-scrollbar-thumb:hover {
      background: #aaa;
    }
    
    .paper-effect {
      background-color: white;
      border-radius: var(--border-radius-lg);
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      padding: var(--spacing-xl);
      max-width: 780px;
      margin: 0 auto;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--color-primary);
        border-radius: var(--border-radius-lg) var(--border-radius-lg) 0 0;
      }
    }
  }
  
  .preview-footer {
    text-align: center;
    
    .preview-tip {
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
      margin: 0;
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    
    .page-title {
      margin-bottom: var(--spacing-md);
    }
  }
  
  .resume-list {
    .resume-card {
      flex-direction: column;
      align-items: flex-start;
      
      .resume-info {
        width: 100%;
        margin-bottom: var(--spacing-md);
        
        .resume-stats {
          flex-wrap: wrap;
          gap: var(--spacing-md);
        }
      }
      
      .resume-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }
  }
}
</style> 